package io.renren.modules.staro2.utils;

import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * @author winson
 * @CREATE 26 15:55
 */
public class DownloadUtils {

    public static String PATH = "/Users/winson/Documents/winson_game/staro2";

    public static void downloadPicture(String urlList, String dir){
        downloadPicture( urlList, dir, PATH ) ;
    }

    public static void downloadPicture(String urlList,String dir, String path) {

        URL url = null;

        try {
            dir = path + "/" + dir;
            // 判断目录是否存在
            if ( !FileUtil.exist( dir ) ){
                FileUtil.mkdir( dir );
            }

            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream( url.openStream());

            String imageName = dir  + "/" + testGetName( urlList );
            File file = new File( imageName );
            if( FileUtil.exist(file) ){
                return;
            }

            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }

            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String testGetName( String url ){
        String name = new Date().getTime() + ".jpg";
        int index = url.lastIndexOf("/");
        if( index != -1 ){
            name = url.substring( index + 1, url.length()  );
        }
        System.out.println( name );
        return name;
    }

}
